// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT
package exporter

import (
        "uos-dovecot-exporter/pkg/logger"
        "uos-dovecot-exporter/pkg/utils"
        "github.com/sirupsen/logrus"
        "github.com/alecthomas/kingpin"
        "gopkg.in/yaml.v2"
        "os"
        "fmt"
        "time"

)

var (
        Configfile    *string
        DefaultConfig = Config{
                Logging: logger.Config{
                        Level:   "debug",
                        LogPath: "/var/log/uos-exporter/uos-dovecot-exporter.log",
                        MaxSize: "10MB",
                        MaxAge:  time.Hour * 24 * 7},
                Address:     "0.0.0.0",
                Port:        9107,
                MetricsPath: "/metrics",
        }
)

func init() {
        kingpin.HelpFlag.Short('h')
        Configfile = kingpin.Flag("config", "Configuration file").
                Short('c').
                Default("/etc/uos-exporter/uos-dovecot-exporter.yaml").
                String()
}

type Config struct {
        Logging     logger.Config `yaml:"log"`
        Address     string        `yaml:"address"`
        Port        int           `yaml:"port"`
        MetricsPath string        `yaml:"metricsPath"`
}

func Unpack(config interface{}) error {
    if !utils.FileExists(*Configfile) {
        logrus.Errorf("Configuration file not found: %s", *Configfile)
        logrus.Info("Using default configuration")
        return nil
    }

    file, err := os.Open(*Configfile)
    if err != nil {
        logrus.Errorf("Failed to open configuration file '%s': %v", *Configfile, err)
        return fmt.Errorf("open config file: %w", err)
    }
    defer file.Close()

    if err := yaml.NewDecoder(file).Decode(config); err != nil {
        logrus.Errorf("Failed to decode configuration from '%s': %v", *Configfile, err)
        return fmt.Errorf("decode YAML config: %w", err)
    }

    logrus.Infof("Successfully loaded configuration from: %s", *Configfile)
    return nil
}
